var core    = require('core')
,   crypto  = require('crypto')
,   send    = core.send
,   db      = core.db
,   schema  = db.schema;

var POST = function(req, res, next){
    var body        = req.body
    ,   app         = req.app
    ,   platformId  = body.platformId
    ,   key         = body.key
    ,   secret      = body.secret
    ,   time        = Date.now()
    ,   platform    = app.platform.item[platformId] || {}
    ,   keys        = function(){
        var key = crypto.createHash('sha1');
        key.update(platform.key + time);
        return key.digest('hex');
    }()
    ,   data        = platform.key === key ? { platform: platformId, key: keys } : {}
    ,   options     = { type : 1, exp : platform.expires }
    ,   token       = res.token(options, data, secret)
    ,   SEND;
    console.log(body);
    if(data.platform){
        var query = {
            pid     : platform.pid
        }
        ,   update = {
            time    : time
        }
        ,   options = {
            new     : true
        }
        return schema.Platform.findOneAndUpdate(query, update, options, function(err, docs){
            if(!err){
                app.platform.item[platformId] = docs;
            };

            SEND = new send(0);
            SEND.docs = {
                token : token
            };
            return res.json(SEND);

        });
    };
    SEND = new send(0);
    SEND.docs = {
        token : token
    };
    return res.json(SEND);

    // SEND.docs = {
        // token : token
    // };

    // res.json(SEND);


};

module.exports = POST;
